package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"modbus/device/analysis"
	"modbus/device/config"
	"modbus/mqttclient"
	"modbus/rpcServer"
	"os"
	"time"
)

var g_collenDev map[string]*analysis.DevInfoTable

func checkDevIPPort(dev *analysis.DevInfoTable) bool {
	if dev.DevInfo.InterType == "RS485" {
		for _, table := range g_collenDev {
			if table.DevInfo.InterName == dev.DevInfo.InterName {
				dev.DevInfo.ModbusClient = table.DevInfo.ModbusClient
				dev.DevInfo.HandleRtuClient = table.DevInfo.HandleRtuClient
				return true
			}
		}

	} else if dev.DevInfo.InterType == "ETHERNET" {
		for _, table := range g_collenDev {
			if table.DevInfo.Address == dev.DevInfo.Address && table.DevInfo.Port == dev.DevInfo.Port {
				dev.DevInfo.ModbusClient = table.DevInfo.ModbusClient
				dev.DevInfo.HandleClient = table.DevInfo.HandleClient
				return true
			}
		}
	}
	return false
}

func initDevClient(client mqtt.Client) {
	for _, table := range g_collenDev {
		table.DevInfo.MqttClient = client
	}
}

var (
	CONFIG_DIR = "./conf/"
)

func InitCfgFile(filename string) {

	stat, _ := os.Stat(filename)
	if stat.IsDir() {
		return
	}
	collenDev, err := config.CollenDev(filename)
	if err != nil {
		if collenDev != nil {
			fmt.Println(collenDev.DevInfo.DevName, collenDev.DevInfo.Address, collenDev.DevInfo.Port)
		}
		panic(err)
	}
	port := checkDevIPPort(collenDev)
	if port == false {
	retrycon:
		err = collenDev.Connect()
		if err != nil {
			fmt.Println(err)
			time.Sleep(time.Second * 3)
			goto retrycon
		}
	}
	g_collenDev[collenDev.DevInfo.DevName] = collenDev
	go collenDev.Start()
}

func main() {
	dir, err2 := os.ReadDir(CONFIG_DIR)
	if err2 != nil {
		panic(err2)
	}
	g_collenDev = make(map[string]*analysis.DevInfoTable)
	for _, entry := range dir {
		InitCfgFile(CONFIG_DIR + entry.Name())
	}
	init := mqttclient.MqttInit("127.0.0.1", 1883, g_collenDev)
	initDevClient(init)
	rpcServer.RpcServer(&g_collenDev)
	for {
		time.Sleep(time.Second)
	}
}
